<script setup lang="ts">
import { request } from '@/api'
import b64toBlob from 'b64-to-blob'
import { closeToast, showLoadingToast, showToast, type ActionSheetAction } from 'vant'
import { onMounted, ref } from 'vue'
const showAvatarSheet = ref(false)
const actions = [{ name: '拍照' }, { name: '相册' }]
const onSelect = async (action: ActionSheetAction, index: number) => {
  if (index === 0) {
    // 拍照上传
    const res = await mk.pickerCamera()
    // 上传图片
    await onUpdateAvatar(res)
  } else if (index === 1) {
    // 相册上传
    const res = await mk.pickerPhoto()
    // 上传图片
    await onUpdateAvatar(res)
  }
}
// 头像图片上传
const onUpdateAvatar = async (data: string) => {
  try {
    // 显示加载提示
    showLoadingToast({ message: '上传中...', duration: 0, forbidClick: true })
    const img = b64toBlob(data, 'image/jpeg')
    const fd = new FormData()
    fd.append('file', img, Date.now() + '.jpeg')
    const res = await request.post<MkResponse<{ avatar: string }>>('/member/profile/avatar', fd)
    // 获取用户数据
    const user = mk.queryUser()
    // 修改用户头像数据
    user.avatar = res.data.result.avatar
    // 更新页面上的头像
    profile.value.avatar = res.data.result.avatar
    // 更新用户数据
    mk.updateUser(user)
    showToast({ message: '上传成功' })
  } catch (error) {
    showToast({ message: '上传失败' })
    console.log(error)
  }
}
// 用户选择的生日数据
const currentDate = ref(['2001', '01', '01'])
const minDate = new Date(1980, 1, 1)
const maxDate = new Date(2025, 11, 31)
// 是否显示日期选择器
const showCandidate = ref(false)
const selectDate = () => {
  // 关闭日期选择器
  showCandidate.value = false
  // 修改生日为用户选择的日期
  profile.value.birthday = currentDate.value.join('-')
}
// 是否显示省市区选择框
const showCityPicker = ref(false)
// 省市区数据
const areaList = ref<AreaColumns>()
onMounted(async () => {
  // 获取省市区数据
  const res1 = await mk.getAreaColumns()
  areaList.value = res1
})
const areaCode = ref('')
const selectArea = ({ selectedValues, selectedOptions, selectedIndexes }) => {
  // 关闭省市区选择框
  showCityPicker.value = false
  // // 打印用户选择的省市区编码
  // console.log(selectedOptions)
  // 修改省市区为用户选择的省市区
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countyCode = selectedValues[2]
  profile.value.fullLocation = selectedOptions.map((item: SelectAreaItem) => item.text).join(' ')
}
//  职业数据列表
const columns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
// 是否显示选择职业弹出框
const showJob = ref(false)
// 选择职业
const selectJob = ({ selectedOptions }) => {
  // 关闭选择职业弹出框
  showJob.value = false
  // // 打印用户选择的职业
  // console.log(selectedOptions[0].value)
  // 修改职业为用户选择的职业
  profile.value.profession = selectedOptions[0].value
}
// 用户信息
const profile = ref<ProfileInfo>({} as ProfileInfo)

onMounted(async () => {
  // 获取用户信息
  showLoadingToast({ message: '加载中...', duration: 0, forbidClick: true })
  const res2 = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  profile.value = res2.data.result
  closeToast()
})

// 存储修改后的用户数据(不包括头像)
const saveData = async () => {
  try {
    showLoadingToast({ message: '保存中...', duration: 0, forbidClick: true })
    await request.put<MkResponse<ProfileInfo>>('/member/profile', profile.value)
    mk.updateUser(profile.value)
    showToast({ message: '保存成功' })
  } catch (error) {
    showToast({ message: '保存失败' })
    console.log(error)
  }
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile?.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
      </div>
    </div>

    <van-action-sheet
      v-model:show="showAvatarSheet"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />
    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field label="昵称" v-model="profile.nickname" placeholder="请输入昵称"></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field
        label="生日"
        readonly
        v-model="profile.birthday"
        placeholder="请选择日期"
        @click="showCandidate = true"
      ></van-field>
      <van-popup v-model:show="showCandidate" position="bottom">
        <van-date-picker
          v-model="currentDate"
          title="选择日期"
          :min-date="minDate"
          :max-date="maxDate"
          @cancel="showCandidate = false"
          @confirm="selectDate"
        />

        /></van-popup
      >

      <van-field
        label="所在地"
        readonly
        v-model="profile.fullLocation"
        placeholder="请选择所在地"
        @click="showCityPicker = true"
      ></van-field>
      <van-popup v-model:show="showCityPicker" position="bottom">
        <van-area
          v-model="areaCode"
          :area-list="areaList"
          @cancel="showCityPicker = false"
          @confirm="selectArea"
        />
      </van-popup>
      <van-field
        label="职业"
        readonly
        placeholder="请选择职业"
        @click="showJob = true"
        v-model="profile.profession"
      ></van-field>
      <van-popup v-model:show="showJob" destroy-on-close round position="bottom">
        <van-picker :columns="columns" @cancel="showJob = false" @confirm="selectJob" />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button round block type="primary" @click="saveData"> 保存资料 </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
